# 基本使用示例
# examples/basic_usage_backup.py
"""
基本使用示例
"""
import requests
import json
import numpy as np
from datetime import datetime, timedelta

# API基础URL
BASE_URL = "http://localhost:8000"

def example_market_change_detection():
    """市场变化检测示例"""
    print("📊 市场变化检测示例")
    
    # 生成模拟数据
    np.random.seed(42)
    returns_matrix = np.random.normal(0.001, 0.02, (60, 5)).tolist()
    
    response = requests.post(
        f"{BASE_URL}/changes/detect",
        json={
            "returns_matrix": returns_matrix,
            "test_method": "ks"
        }
    )
    
    if response.status_code == 200:
        result = response.json()
        print(f"✅ 检测结果: {result}")
        print(f"是否变化: {'是' if result['is_change'] else '否'}")
        print(f"P值: {result['p_value']:.4f}")
    else:
        print(f"❌ 请求失败: {response.text}")

def example_portfolio_optimization():
    """投资组合优化示例"""
    print("\n💼 投资组合优化示例")
    
    response = requests.post(
        f"{BASE_URL}/optimize/run",
        json={
            "assets": ["AAPL", "MSFT", "GOOGL", "TSLA", "NVDA"],
            "objectives": {
                "return_weight": 0.5,
                "risk_weight": 0.3,
                "esg_weight": 0.2,
                "cost_weight": 0.0
            },
            "constraints": {
                "max_single_weight": 0.3,
                "min_cash_ratio": 0.1,
                "max_sector_weight": 0.4,
                "max_turnover": 0.5
            },
            "algorithm": "nsga2",
            "start_date": "2023-01-01",
            "end_date": "2023-12-31"
        }
    )
    
    if response.status_code == 200:
        result = response.json()
        print(f"✅ 优化完成")
        print(f"算法: {result['algorithm']}")
        print(f"执行时间: {result['execution_time']:.2f}秒")
        print(f"Pareto解数量: {len(result['pareto_set'])}")
        
        # 显示最优解
        if result['pareto_set']:
            best_solution = result['pareto_set'][0]
            print(f"\n🏆 示例解:")
            print(f"权重分配: {json.dumps(best_solution['weights'], indent=2)}")
            print(f"指标: {json.dumps(best_solution['metrics'], indent=2)}")
    else:
        print(f"❌ 优化失败: {response.text}")

def example_sac_training():
    """SAC训练示例"""
    print("\n🤖 SAC训练示例")
    
    response = requests.post(
        f"{BASE_URL}/train/sac",
        json={
            "assets": ["AAPL", "MSFT", "GOOGL", "TSLA", "NVDA"],
            "start_date": "2023-01-01",
            "end_date": "2023-12-31",
            "episodes": 500
        }
    )
    
    if response.status_code == 200:
        result = response.json()
        print(f"✅ {result['message']}")
        print(f"状态: {result['status']}")
    else:
        print(f"❌ 训练启动失败: {response.text}")

def example_visualization():
    """可视化示例"""
    print("\n📈 可视化示例")
    
    # 模拟Pareto解集
    pareto_set = [
        {
            "weights": {"AAPL": 0.3, "MSFT": 0.2, "GOOGL": 0.2, "TSLA": 0.15, "NVDA": 0.15},
            "metrics": {"expected_return": 0.12, "risk": 0.18, "esg_score": 82}
        },
        {
            "weights": {"AAPL": 0.25, "MSFT": 0.25, "GOOGL": 0.2, "TSLA": 0.15, "NVDA": 0.15},
            "metrics": {"expected_return": 0.10, "risk": 0.15, "esg_score": 85}
        },
        {
            "weights": {"AAPL": 0.2, "MSFT": 0.3, "GOOGL": 0.2, "TSLA": 0.15, "NVDA": 0.15},
            "metrics": {"expected_return": 0.08, "risk": 0.12, "esg_score": 88}
        }
    ]
    
    response = requests.post(
        f"{BASE_URL}/visualize/pareto",
        json={
            "pareto_set": pareto_set,
            "user_preferences": {
                "return_preference": 0.5,
                "risk_preference": 0.3,
                "esg_preference": 0.2
            }
        }
    )
    
    if response.status_code == 200:
        result = response.json()
        print("✅ 可视化数据生成成功")
        print("📊 可视化组件已准备就绪")
    else:
        print(f"❌ 可视化失败: {response.text}")

if __name__ == "__main__":
    print("🚀 动态多目标投资组合优化系统 - 使用示例")
    print("=" * 50)
    
    # 检查API服务是否可用
    try:
        response = requests.get(f"{BASE_URL}/health")
        if response.status_code == 200:
            print("✅ API服务运行正常\n")
            
            # 运行示例
            example_market_change_detection()
            example_portfolio_optimization()
            example_sac_training()
            example_visualization()
            
        else:
            print("❌ API服务不可用")
    except requests.exceptions.ConnectionError:
        print("❌ 无法连接到API服务，请确保服务正在运行")
